package com.item.yxlottery.yxlottery.activity;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2017/1/16 09:23
 * @文件描述    用户登录
 *------------------------------
 */

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.utils.RegexUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.base.BaseActivity;
import com.item.yxlottery.yxlottery.callback.MyStringCallBack;
import com.item.yxlottery.yxlottery.common.Constant;
import com.item.yxlottery.yxlottery.utils.AesUtil;
import com.item.yxlottery.yxlottery.utils.UrlUtil;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.cet_login_phone)
    EditText mCetPhone;

    @Bind(R.id.cet_login_password)
    EditText mCetPassword;

    @Bind(R.id.cb_login_rememberpassword)
    CheckBox mCbRememberPassword;

    @Bind(R.id.bt_login_login)
    Button mBtLogin;

    @Bind(R.id.tv_login_forgetpassword)
    TextView mTvForgetPassword;

    @Bind(R.id.tv_login_regist)
    TextView mTvRegist;

    @Override
    protected void setCustomActionBar(ImageButton ibActionbarLeft, TextView tvActionBarTitle, ImageButton ibActionbarRight, AutoRelativeLayout layoutActionbar) {
        ibActionbarLeft.setImageResource(R.drawable.leftarrow);
        ibActionbarLeft.setOnClickListener(this);
        ibActionbarRight.setVisibility(View.GONE);
        tvActionBarTitle.setText("登录");
    }

    @Override
    protected View initView() {
        View view = View.inflate(this, R.layout.activity_login, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        //是否记住密码
        Boolean remember = Hawk.get("remember", false);
        mCbRememberPassword.setChecked(remember);
        if (remember) {
            String password = Hawk.get("password", "");
            String username = Hawk.get("username", "");
            String decrypt = AesUtil.decrypt(username, Constant.KEY);
            mCetPhone.setText(decrypt);
            mCetPhone.setSelection(decrypt.length());
            mCetPassword.setText(AesUtil.decrypt(password, Constant.KEY));
        }
    }

    @Override
    protected void initEvent() {
        mBtLogin.setOnClickListener(this);
        mTvForgetPassword.setOnClickListener(this);
        mTvRegist.setOnClickListener(this);
        mCetPhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (RegexUtils.isMobileExact(charSequence)) {
                    mCetPhone.setTextColor(Color.BLACK);
                } else {
                    mCetPhone.setTextColor(Color.RED);
                }
                mCetPhone.setSelection(charSequence.length());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mCbRememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Hawk.put("remember", b);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_actionbar_left:
                finish();
                break;
            case R.id.bt_login_login://登录
                String phone = mCetPhone.getText().toString();
                String password = mCetPassword.getText().toString();
                if (phone.isEmpty()) {
                    ToastUtils.showShortToastSafe(this, "手机号码不能为空");
                    return;
                }
                if (mCetPhone.getCurrentTextColor() == Color.RED) {
                    ToastUtils.showShortToastSafe(this, "手机号码格式不正确");
                    return;
                }
                if (password.isEmpty()) {
                    ToastUtils.showShortToastSafe(this, "登录密码不能为空");
                    return;
                }
                OkHttpUtils.post().url(UrlUtil.getLoginUrl()).addParams("userName", phone).addParams("password", password)
                        .build().execute(new MyStringCallBack(this, true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject parse = (JSONObject) JSON.parse(response);

                        if (parse.getString("error_code").equals(Constant.SUCCESS)) {
                            //保存登陆信息
                            JSONObject attrs = (JSONObject) JSON.parse(parse.getString("attrs"));
                            JSONObject member = (JSONObject) JSON.parse(attrs.getString("member"));
                            Hawk.put("appToken",attrs.getString("appToken")); // 用户appToken
                            Hawk.put("memberTruename",member.getString("memberTruename")); // 用户真实姓名
                            Hawk.put("memberName",member.getString("memberName"));// 帐号名，手机号
                            Hawk.put("memberAvatar",member.getString("memberAvatar"));// 用户头像地址

                            Logger.d(Hawk.get("remember",false));
                            if (Hawk.get("remember",false)) {
                                String username = AesUtil.encrypt(mCetPhone.getText().toString(), Constant.KEY);//加密
                                String password = AesUtil.encrypt(mCetPassword.getText().toString(), Constant.KEY);
                                Hawk.put("username",username);
                                Hawk.put("password", password);
                            } else {
                                Hawk.put("username", "");
                                Hawk.put("password", "");
                            }
                            LoginActivity.this.finish();
                        } else {
                            ToastUtils.showShortToastSafe(LoginActivity.this, parse.getString("msg"));
                        }
                    }
                });
                break;
            case R.id.tv_login_forgetpassword://忘记密码

                break;
            case R.id.tv_login_regist://注册
                startActivity(new Intent(this, RegistActivity.class));
                break;
        }
    }
}
